from keras.datasets import mnist
from keras import backend
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation,Flatten,Convolution2D,MaxPool2D



'''
1、读数据
2、构造卷积神经网络
3、调整参数【a、每个参数每次选择最佳的。b、一次全调。】

参考的代码的疑问：1、第二层没有指定inpt_shape   2、未设定stride

可以调整的参数：
激活函数 
正则化 (正则化因子 )
权重初始化 
卷积 
池化 
学习率 
'''


#定义全局变量
batch_size = 128
epochs = 30
img_rows, img_cols = 28,28
nb_filter = 32#kernel的个数
pool_size= (2,2)
kernel_size = (3,3)
activationName = "relu"



(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
#将图片格式配置成（channel,height,width)
backend.set_image_dim_ordering('th')
X_train = X_train.reshape(X_train.shape[0],1,28,28)
X_test = X_test.reshape(X_test.shape[0],1,28,28)
input_shape = (1,img_rows,img_cols)

#将训练集和测试集归一化
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32')   / 255

#将训练集和测试集结果进行one_hot
Y_train = np_utils.to_categorical(Y_train,10)
Y_test = np_utils.to_categorical(Y_test,10)

#创建模型:两层卷积，两层全连接
model = Sequential()
#两层卷积
model.add(Convolution2D(nb_filter,kernel_size=kernel_size,padding='same',input_shape=input_shape,strides=2))
model.add(Activation(activationName))

model.add(Convolution2D(nb_filter,kernel_size=kernel_size,input_shape=input_shape,strides=2))
model.add(Activation(activationName))
#池化
model.add(MaxPool2D(pool_size=pool_size))
# model.add(Dropout(0.25))#神经元随机失活
#加上2层全连接层，最后一层作为输出，使用softmax函数
model.add(Flatten())
model.add(Dense(128))
model.add(Activation(activationName))
# model.add(Dropout(0.5))#神经元随机失活
model.add(Dense(10))#因为最后的输出也是10维
model.add(Activation("softmax"))

#编译模型
model.compile(
    loss='categorical_crossentropy',
    optimizer='adadelta',
    metrics=['accuracy']
)

#训练模型
model.fit(X_train,Y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=[X_test,Y_test])

#评估模型
score = model.evaluate(X_test,Y_test,verbose=0)

print("损失函数值：",score[0])
print("准  确  率：",score[1])







